package utils

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/http/cookiejar"
	"strings"
	"time"
	"webserver/app/define"
)

var client *http.Client

func init() {
	client = &http.Client{
		Timeout: 5 * time.Second,
		Transport: &http.Transport{
			IdleConnTimeout:     3 * time.Minute,
			TLSHandshakeTimeout: 5 * time.Second,
			DialContext: (&net.Dialer{
				Timeout:   5 * time.Second,
				KeepAlive: 10 * time.Minute,
				DualStack: true,
			}).DialContext,
		},
	}
}

// 发送GET请求
func HttpGet(url string, header []*define.AjaxHeaderReq) ([]byte, error) {
	req, err := http.NewRequest("GET", url, nil)
	//req.Header.Set("Content-Type", "application/json")
	//req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.55")
	//req.Header.Set("Referer", "https://xueqiu.com/S/SH019547")
	//req.Header.Set("origin", "https://xueqiu.com")
	//req.Header.Set("cookie", "https://xueqiu.com")

	if header != nil && len(header) > 0 {
		for _, row := range header {
			req.Header.Set(row.Key, row.Val)
		}
	}

	rsp, err := client.Do(req)
	//rsp, err := client.Get(url)
	if err != nil {
		return nil, err
	}
	defer rsp.Body.Close()
	return ioutil.ReadAll(rsp.Body)
}

// 发送通用的POST请求
func HttpPost(url string, body interface{}, header []*define.AjaxHeaderReq) ([]byte, error) {
	bodyStr, err := json.Marshal(body)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest("POST", url, strings.NewReader(string(bodyStr)))
	//req.Header.Set("Content-Type", contentType)
	//req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.55")
	////req.Header.Set("Host", "danjuanapp.com")
	//req.Header.Set("Referer", "https://danjuanapp.com/djmodule/value-center?channel=1300100141")

	if header != nil && len(header) > 0 {
		for _, row := range header {
			req.Header.Set(row.Key, row.Val)
		}
	}

	rsp, err := client.Do(req)

	//rsp, err := client.Post(url, contentType, strings.NewReader(body))

	if err != nil {
		return nil, err
	}
	defer rsp.Body.Close()
	return ioutil.ReadAll(rsp.Body)
}

func HttpResultToJson(body []byte) (interface{}, error) {
	//str := string(body[:])
	//if str == "" {
	//    return nil, errors.New("获取数据失败")
	//}

	var jsonObj *interface{}
	err := json.Unmarshal(body, &jsonObj)
	return jsonObj, err
}

func GetUrlCookie(url string, header []*define.AjaxHeaderReq) (interface{}, error) {
	fmt.Printf("\ngetUrlRespHtml, url=%s", url)

	//var respHtml string = ""
	var gCurCookies []*http.Cookie
	var gCurCookieJar *cookiejar.Jar
	gCurCookies = nil
	gCurCookieJar, _ = cookiejar.New(nil)

	httpClient := &http.Client{
		CheckRedirect: nil,
		Jar:           gCurCookieJar,
	}

	httpReq, err := http.NewRequest("GET", url, nil)

	if header != nil {
		for _, row := range header {
			httpReq.Header.Set(row.Key, row.Val)
		}
	} else {
		httpReq.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.55")
	}

	httpResp, err := httpClient.Do(httpReq)
	if err != nil {
		fmt.Printf("\nhttp get url=%s response error=%s\n", url, err.Error())
		return nil, err
	}
	fmt.Printf("\nhttpResp.Header=%s", httpResp.Header)
	fmt.Printf("\nhttpResp.Status=%s", httpResp.Status)

	defer httpResp.Body.Close()

	_, errReadAll := ioutil.ReadAll(httpResp.Body)
	if errReadAll != nil {
		fmt.Printf("\nget response for url=%s got error=%s\n", url, errReadAll.Error())
	}

	gCurCookies = gCurCookieJar.Cookies(httpReq.URL)

	//respHtml = string(body)
	//return respHtml
	return gCurCookies, nil
}

func GetUrlHtml(url string, header []*define.AjaxHeaderReq) (string, error) {
	fmt.Printf("\ngetUrlRespHtml, url=%s", url)

	var respHtml string = ""
	// var gCurCookies []*http.Cookie
	var gCurCookieJar *cookiejar.Jar
	// gCurCookies = nil
	gCurCookieJar, _ = cookiejar.New(nil)

	httpClient := &http.Client{
		CheckRedirect: nil,
		Jar:           gCurCookieJar,
	}

	httpReq, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Printf("\nhttp get url=%s response error=%s\n", url, err.Error())
		return "", err
	}

	if header != nil {
		for _, row := range header {
			httpReq.Header.Set(row.Key, row.Val)
		}
	} else {
		httpReq.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.55")
	}

	fmt.Printf("\nhttpReq.Header=%s", httpReq.Header)

	httpResp, err := httpClient.Do(httpReq)
	if err != nil {
		fmt.Printf("\nhttp get url=%s response error=%s\n", url, err.Error())
		return "", err
	}
	fmt.Printf("\nhttpResp.Header=%s", httpResp.Header)
	fmt.Printf("\nhttpResp.Status=%s", httpResp.Status)

	defer httpResp.Body.Close()

	body, errReadAll := ioutil.ReadAll(httpResp.Body)
	if errReadAll != nil {
		fmt.Printf("\nget response for url=%s got error=%s\n", url, errReadAll.Error())
	}

	// gCurCookies = gCurCookieJar.Cookies(httpReq.URL)

	respHtml = string(body)
	return respHtml, nil
}
